<template>
  <div class="login-container">
    <!-- 背景装饰 -->
    <div class="login-bg">
      <div class="bg-decoration"></div>
      <div class="bg-circles">
        <div class="circle circle-1"></div>
        <div class="circle circle-2"></div>
        <div class="circle circle-3"></div>
      </div>
    </div>

    <!-- 登录表单 -->
    <div class="login-content">
      <div class="login-form-container">
        <!-- Logo和标题 -->
        <div class="login-header">
          <div class="logo">
            <img src="/favicon.ico" alt="FreePortal" class="logo-icon" />
            <h1 class="logo-text">FreePortal</h1>
          </div>
          <p class="login-subtitle">现代化企业级管理平台</p>
        </div>

        <!-- 登录表单 -->
        <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" class="login-form" size="large"
          @keyup.enter="handleLogin">
          <el-form-item prop="username">
            <el-input v-model="loginForm.username" placeholder="请输入用户名" :prefix-icon="User" clearable
              @keyup.enter="handleLogin" />
          </el-form-item>

          <el-form-item prop="password">
            <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" :prefix-icon="Lock" show-password
              @keyup.enter="handleLogin" />
          </el-form-item>

          <el-form-item prop="captcha" v-if="showCaptcha">
            <div class="captcha-container">
              <el-input v-model="loginForm.captcha" placeholder="请输入验证码" :prefix-icon="Key" class="captcha-input"
                @keyup.enter="handleLogin" />
              <div class="captcha-code" @click="refreshCaptcha">
                {{ captchaCode }}
              </div>
            </div>
          </el-form-item>

          <el-form-item>
            <div class="login-options">
              <el-checkbox v-model="rememberMe">记住密码</el-checkbox>
              <el-link type="primary" :underline="false">忘记密码？</el-link>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" class="login-btn" :loading="loading" @click="handleLogin">
              {{ loading ? '登录中...' : '登录' }}
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 底部信息 -->
        <div class="login-footer">
          <p class="copyright">© 2024 FreePortal. All rights reserved.</p>
          <div class="version-info">
            <span>Version 1.0.0</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElForm } from 'element-plus'
import { User, Lock, Key } from '@element-plus/icons-vue'

const router = useRouter()
const loginFormRef = ref<InstanceType<typeof ElForm>>()

// 表单数据
const loginForm = reactive({
  username: 'admin',
  password: '123456',
  captcha: ''
})

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 4, message: '验证码为4位字符', trigger: 'blur' }
  ]
}

// 状态管理
const loading = ref(false)
const rememberMe = ref(false)
const showCaptcha = ref(true)
const captchaCode = ref('AB3D')

// 刷新验证码
const refreshCaptcha = () => {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
  let result = ''
  for (let i = 0; i < 4; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  captchaCode.value = result
}

// 登录处理
const handleLogin = async () => {
  if (!loginFormRef.value) return

  try {
    await loginFormRef.value.validate()

    if (showCaptcha.value && loginForm.captcha.toUpperCase() !== captchaCode.value) {
      ElMessage.error('验证码错误')
      refreshCaptcha()
      loginForm.captcha = ''
      return
    }

    loading.value = true

    // 模拟登录请求
    setTimeout(() => {
      loading.value = false

      // 简单的用户名密码验证
      if (loginForm.username === 'admin' && loginForm.password === '123456') {
        ElMessage.success('登录成功')

        // 保存登录状态
        localStorage.setItem('isLoggedIn', 'true')
        localStorage.setItem('username', loginForm.username)

        if (rememberMe.value) {
          localStorage.setItem('rememberMe', 'true')
          localStorage.setItem('savedUsername', loginForm.username)
        }

        // 跳转到主页
        router.push('/dashboard')
      } else {
        ElMessage.error('用户名或密码错误')
        refreshCaptcha()
        loginForm.captcha = ''
      }
    }, 2000)

  } catch (error) {
    console.log('表单验证失败:', error)
  }
}

// 组件挂载时的处理
onMounted(() => {
  // 检查是否已登录
  if (localStorage.getItem('isLoggedIn') === 'true') {
    router.push('/dashboard')
    return
  }

  // 如果记住密码，自动填充用户名
  if (localStorage.getItem('rememberMe') === 'true') {
    const savedUsername = localStorage.getItem('savedUsername')
    if (savedUsername) {
      loginForm.username = savedUsername
      rememberMe.value = true
    }
  }

  // 初始化验证码
  refreshCaptcha()
})
</script>

<style scoped>
.login-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.login-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.bg-decoration {
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="50" cy="50" r="1" fill="rgba(255,255,255,0.1)"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>');
  animation: float 20s infinite linear;
}

.bg-circles {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.circle {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 15s infinite ease-in-out;
}

.circle-1 {
  width: 80px;
  height: 80px;
  top: 20%;
  left: 10%;
  animation-delay: 0s;
}

.circle-2 {
  width: 120px;
  height: 120px;
  top: 60%;
  right: 15%;
  animation-delay: 5s;
}

.circle-3 {
  width: 60px;
  height: 60px;
  bottom: 20%;
  left: 20%;
  animation-delay: 10s;
}

@keyframes float {

  0%,
  100% {
    transform: translateY(0px) rotate(0deg);
  }

  50% {
    transform: translateY(-20px) rotate(180deg);
  }
}

.login-content {
  position: relative;
  z-index: 10;
  width: 100%;
  max-width: 400px;
  padding: 20px;
}

.login-form-container {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 40px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.logo {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
}

.logo-icon {
  width: 48px;
  height: 48px;
  margin-right: 12px;
}

.logo-text {
  font-size: 32px;
  font-weight: bold;
  color: #333;
  margin: 0;
  background: linear-gradient(135deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.login-subtitle {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.login-form {
  margin-bottom: 30px;
}

.login-form .el-form-item {
  margin-bottom: 24px;
}

.captcha-container {
  display: flex;
  gap: 12px;
}

.captcha-input {
  flex: 1;
}

.captcha-code {
  width: 100px;
  height: 40px;
  background: linear-gradient(45deg, #f0f0f0, #e0e0e0);
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 16px;
  letter-spacing: 2px;
  cursor: pointer;
  user-select: none;
  transition: all 0.3s;
}

.captcha-code:hover {
  background: linear-gradient(45deg, #e0e0e0, #d0d0d0);
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.login-btn {
  width: 100%;
  height: 44px;
  font-size: 16px;
  font-weight: 500;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border: none;
  border-radius: 8px;
  transition: all 0.3s;
}

.login-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4);
}

.login-footer {
  text-align: center;
  color: #999;
  font-size: 12px;
}

.copyright {
  margin: 0 0 8px 0;
}

.version-info {
  color: #ccc;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-content {
    padding: 10px;
  }

  .login-form-container {
    padding: 30px 20px;
    border-radius: 15px;
  }

  .logo-text {
    font-size: 28px;
  }

  .captcha-container {
    flex-direction: column;
  }

  .captcha-code {
    width: 100%;
  }
}
</style>
